package com.gitee.huanminabc.utils_tools.security.service.impl;

import com.gitee.huanminabc.utils_tools.security.entity.UserEntity;
import com.gitee.huanminabc.utils_tools.security.service.UserDetailsService;
import com.gitee.huanminabc.utils_tools.security.service.UserService;
import com.gitee.huanminabc.utils_tools.security.vo.LoginUserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

//固定格式必须是userDetailsService
@Service("userDetailsService")
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Override
    public org.springframework.security.core.userdetails.UserDetails loadUserByUsername(String account) throws org.springframework.security.core.userdetails.UsernameNotFoundException {
        if (Strings.isBlank(account)){
            throw new UsernameNotFoundException("用户名不能为空");
        }
        UserEntity user = userService.getUser(account);
        if (user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        //从数据库中取出用户的角色列表,开头必须是ROLE_xxx，否则报错
        List<String> roles = userService.getRoles(account);
        return  new LoginUserVo(user, roles);
    }
}
